package com.acmen.easyapi.factory;

import com.acmen.easyapi.concurrent.TestCallable;
import com.alibaba.fastjson.JSON;
import com.acmen.easyapi.model.Api;
import com.acmen.easyapi.model.RequestData;
import com.acmen.easyapi.model.Response;
import com.acmen.easyapi.dto.UnitTestAdd;
import com.acmen.easyapi.repository.UnitTestRepository;
import com.acmen.easyapi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author acmen
 * 测试Callable工厂
 */
@Component
public class TestCallableFactory {

    @Autowired
    private UnitTestRepository unitTestRepository;

    public List<TestCallable> createCallables(List<Api> apis, String basePath, Map<String, String>  headers) {
        return createCallables(apis, basePath,headers,1);
    }

    /**
     * 创建并发任务列表
     * @param basePath
     * @param concurrency
     * @param headers
     * @return
     */
    public List<TestCallable> createCallables(List<Api> apis,String basePath, Map<String, String>  headers, int concurrency) {
        List<TestCallable> testCallables = new ArrayList<>();
        for(Api api : apis){
            List<UnitTestAdd> unitTests = unitTestRepository.selectCombTestList(api.getId());
            for(UnitTestAdd unitTest : unitTests){
                RequestData requestData = new RequestData();
                if(StringUtil.isNotEmpty(unitTest.getHeaders())){
                    requestData.setHeaders(JSON.parseObject(unitTest.getHeaders()));
                }
                if(StringUtil.isNotEmpty(unitTest.getParams())){
                    requestData.setParams(JSON.parseObject(unitTest.getParams()));
                }
                if(StringUtil.isNotEmpty(unitTest.getBody())){
                    requestData.setBody((JSON)JSON.parse(unitTest.getBody()));
                }
                Response expectResponse = Response.success();
                if(StringUtil.isNotEmpty(unitTest.getResult())){
                    try{
                        expectResponse = JSON.parseObject(unitTest.getResult(),Response.class);
                        expectResponse.setData(null);
                    }catch (Exception e){}
                }
                for(int i=0;i<concurrency;i++){
                    TestCallable callable = new TestCallable(unitTest.getName(),basePath, api,headers, requestData,expectResponse);
                    testCallables.add(callable);
                }
            }
        }
        return testCallables;
    }
}
